import { MutableRefObject } from 'react';
import { extendApi } from '@inbiz/utils';
import { getOriginValueFormat, IProps } from './index';
import { getSaveValue } from './util';
import { MemberTypeKeyMap } from './consts';

export default extendApi((_events: MutableRefObject<IProps['callBackEvents']>, props: IProps) => {
  return {
    getText() {
      try {
        return props.value ? props.value.map((v) => v.name).join(',') : '';
      } catch (e) {
        console.error(e);
        return '';
      }
    },
    getSaveData: () => {
      let _tabs = props.tabs?.filter((item: any) => !item?.hide);
      const userDepartmentDisplayFormat = props.tabs?.find((item: any) => item?.memberKey == 'user')?.departmentDisplayFormat;
      const userUserGroupDisplayFormat = props.tabs?.find((item: any) => item?.memberKey == 'user')?.userGroupDisplayFormat;
      return {
        value: props.value?.map((item: any) => getSaveValue(item, _tabs.length > 1, _tabs, userDepartmentDisplayFormat, userUserGroupDisplayFormat)).join(','),
        childData:
          props.storageConfig && props.childModelConfig
            ? {
                controlId: props.controlId,
                modelKey: props.storageConfig?.business,
                datas: [
                  ...props.value?.map((item: any) => {
                    return props.storageConfig?.tableData.reduce((pre: any, next: any) => {
                      pre[next.modelAttr] = item[next.componentAttr];
                      pre['_opt'] = 'add';
                      return pre;
                    }, {});
                  }),
                  {
                    _opt: 'del',
                  },
                ],
              }
            : undefined,
      };
    },
    setValueToID: async (
      data:
        | {
            memberType: keyof typeof MemberTypeKeyMap;
            memberIds: string[];
          }
        | {
            memberType: keyof typeof MemberTypeKeyMap;
            memberIds: string[];
          }[],
    ) => {
      const params = Array.isArray(data) ? data : [data];
      const ids = params
        .map((item) => item.memberIds.map((id) => `${MemberTypeKeyMap[item.memberType]}:${id}`))
        .flat()
        .join(',');
      const list = await getOriginValueFormat(ids, props);
      props.onChange(list);
      return list;
    },
  };
});

